/**
 * 每日账单
 * @author zhangqiang
 * @date   2016/12/29
 *
 **/

import NoData from "../components/NoData";
import PullRefresh from "../components/mui/PullRefresh.js";

(function (lf, r) {
    var ajax = lf.utils.ajax,
        RC = r.createClass,
        getUrlParam = lf.utils.getUrlParam,
        doAction = lf.appJs.doAction;

    const TYPE = getUrlParam('type'),
        UNTREATED = 'untreated',//未处理
        COMPLETED = 'completed',//已完成
        ARCHIVED = 'archived',//已归档
        CLOSE = 'close',//已关闭
        QLLIGCP = 'qlligcp',//待审核
        SENTED = 'sented',//已派单
        CHECK = 'check';//全部报事

    const ALL = 'all',
          MONTH = 'month';

    let Header = r.createClass({
        getInitialState: function () {
            return {
                headers: [
                    {
                        title: '日汇总',
                        range: ALL,
                    },
                    {
                        title: '销售明细',
                        range: MONTH
                    },
                ],
                counts: [],
                userId: '',
            }
        },
        componentDidMount: function () {
            let $links = $('.header a'),
                me = this;

            if (!$links.length) return;
            //默认第一个点中
            $links.eq(0).addClass('active');
            //点击
            $links.each(function () {
                $(this).on('tap', function () {
                    //切换样式,
                    $(this).addClass('active').siblings().removeClass('active');
                    var range = $(this).data('range');
                    me.props.getList(1, false, range);
                    if (TYPE == CHECK) {
                        me.props.resetPage();
                        mui('#pullrefresh').pullRefresh().refresh(true);//refresh again
                    }
                }.bind(this));
            });
        },
        render: function () {
           let addClass = '',
                headers = this.state.headers.map(function (data, i) {
                    return (
                        <a key={'head-'+i} data-range={data.range} className="item" href="javascript:;">
                            <p className="bold">{data.title}</p>
                            <div className="rectangle"></div>
                        </a>
                    );
                });
            return (
                <div className={"header "+ addClass}>
                    <div className="item-row">
                        {headers}
                    </div>
                    <div className="split-line"></div>
                </div>
            )
        },
    });
    var ListGroup = RC({///日汇总
        getInitialState: function () {
            return ({
                noData: {
                    span_text: '还没有需要您需要的账单',
                    headerCounts: [0, 0],
                }
            });
        },
        render: function () {
            var setList = this.props.data.map(function (data) {
                return (
                    <List data={data}/>
                )
            })
            if (this.props.data.length) {
                return (
                    <div className="list-census" id="listGroup">
                        {setList}
                    </div>
                )
            } else {
                return <NoData data={this.state.noData}/>
            }
        }
    });
    var List = RC({//日汇总
        render: function () {
            var data = this.props.data,
                fmt = 'yyyy-MM-dd hh:mm',
                reportTime = lf.utils.format(data.createTime, fmt),
                reviewStatus = this.props.data.reviewStatus;
            return (
                <a className="list mui-table-view" href="javascript:;" ref="toDetail">
                    <p className="loan ">
                        <span className="introduce">{reportTime}</span>
                    </p>
                    <p className="loan ">
                        <span className="introduce">拍下支付金额：</span>
                        <span className="money green">{'+'+data.snapped}</span>
                    </p>
                    <p className="loan ">
                        <span className="introduce">确认收货金额：</span>
                        <span className="money green">{'+'+data.confirm}</span>
                    </p>
                    <p className="loan ">
                        <span className="introduce">支付宝到账金额：</span>
                        <span className="money green">{'+'+data.Alipay}</span>
                    </p>
                    <p className="loan ">
                        <span className="introduce">售后退款金额：</span>
                        <span className="money pink">{'-'+data.total}</span>
                    </p>
                    {/*
                         <div className="list-title">
                         <span className="name">{data.num} {data.name}</span>
                         <span className="time">{reportTime}</span>
                         </div>
                         <p className="list-text">{data.content}</p>
                         <span className="list-name">{data.accepterName}</span>
                    */}
                </a>
            )
        },
        componentDidMount: function () {
            if (TYPE == UNTREATED) {//待处理
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                        this.props.data.orderId = '';
                    }
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'UNTREATED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == COMPLETED) {//已完成
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&type=' + 'COMPLETED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == ARCHIVED) {//已归档
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'ARCHIVED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == CLOSE) {//已关闭
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId
                        + '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' +
                        'fn' + '&type=' + 'CLOSE'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == QLLIGCP) {//待审核
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'QLLIGCP'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == SENTED) {//已派单
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'SENTED'
                        , '报事详情');
                }.bind(this));
            }
        }
    });

    var LisTotal = RC({///销售总量
        getInitialState: function () {
            return ({
                noData: {
                    span_text: '还没有需要您需要的账单',
                    headerCounts: [0, 0],
                }
            });
        },

        componentDidMount() {
            var s=0;
            $(".prod-detail").each(function(){
                //s+=parseInt($(this).find('input[class*=text_box]').val()) *parseFloat($(this).find('span[class*=price]').text());//这可以跟单价相乘
                s+=parseInt($(this).find('.num').text())*parseFloat($('.prod-detail').length);

                console.log(s)
                console.log($('.prod-detail').length)
            });
            $(".total").html(s.toFixed(2));
        },
        render: function () {
            var setList = this.props.data.map(function (data) {
                return (
                    <ListData data={data}/>
                )
            })
            if (this.props.data.length) {
                return (
                    <div className="list-census" id="listGroup">
                        {setList}
                        <div className="mui-table-view-cell statistics ">
                            <p><span>合计</span><span>:</span><span className="total">12200</span></p>
                        </div>
                    </div>
                )
            } else {
                return <NoData data={this.state.noData}/>
            }
        }
    });
    var ListData = RC({///销售总量
        render: function () {
            var data = this.props.data,
                fmt = 'yyyy-MM-dd hh:mm',
                reportTime = lf.utils.format(data.createTime, fmt),
                reviewStatus = this.props.data.reviewStatus;
            return (
                <a className="list mui-table-view-cell" href="javascript:;" ref="toDetail">
                    <div className="prod-img">
                        <img src={data.img} alt=""/>
                    </div>
                    <div className="prod-detail">
                        <p className="title-box">{data.content}</p>
                        <div className="sales-box">
                            <p className="sales"><span>销量：</span><span>{data.num}</span></p>
                            <p className="total"><span>共计：</span><span>￥</span><span className="num">{data.totle}</span></p>
                        </div>
                    </div>
                </a>
            )
        },
        componentDidMount: function () {

            if (TYPE == UNTREATED) {//待处理
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                        this.props.data.orderId = '';
                    }
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'UNTREATED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == COMPLETED) {//已完成
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&type=' + 'COMPLETED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == ARCHIVED) {//已归档
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn' +
                        '&type=' + 'ARCHIVED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == CLOSE) {//已关闭
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId
                        + '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' +
                        'fn' + '&type=' + 'CLOSE'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == QLLIGCP) {//待审核
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'QLLIGCP'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == SENTED) {//已派单
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&orderId=' + this.props.data.orderId + '&id=' + this.props.data.id + '&last=' + 'fn'
                        + '&type=' + 'SENTED'
                        , '报事详情');
                }.bind(this));
            } else if (TYPE == CHECK) {//全部报事
                if (this.props.data.orderId == undefined || this.props.data.orderId == '') {
                    this.props.data.orderId = '';
                }
                r.findDOMNode(this.refs.toDetail).addEventListener('tap', function () {
                    doAction('report-particulars.html?eventId=' + this.props.data.eventId +
                        '&state=' + this.props.data.status + '&orderId=' + this.props.data.orderId + '&id='
                        + this.props.data.id + '&last=' + 'fn' + '&type=' + 'CHECK'
                        , '报事详情');
                }.bind(this));
            }
        }
    });

    var SelectMonth = r.createClass({
        getInitialState() {
            return {
                title: '',
                sun: 0,
            }
        },

        componentWillMount() {
            this.GetDateStr(0)
        },
        componentDidUpdate() {

        },
        GetDateStr:function(AddDayCount){
            let time = new Date();
            time.setDate(time.getDate()+AddDayCount);//获取AddDayCount天后的日期
            let y = time.getFullYear(),
                 m = time.getMonth()+1,//获取当前月份的日期
                 d = time.getDate();
            this.setState({
                title:y+'年'+m+'月'+d+'日',
            })
            console.log(this.state.title)
        },

        // GetDateStr: function () {
        //     this.setState({liked: this.state.liked >= 2 ? --this.state.liked : this.state.liked});
        // },

        componentDidMount() {
            var me=this;
            $(r.findDOMNode(this.refs.left)).on('tap', ()=> {
                me.GetDateStr(--this.state.sun)
            })
            $(r.findDOMNode(this.refs.right)).on('tap', ()=> {
                me.GetDateStr(++this.state.sun)
            })
        },

        render:function(){
            return(
                <div className="flex select-month">
                    <p className="flex-item">
                        <span ref='left' className="arrowleft mui-icon mui-icon-arrowleft"></span>
                        <span className=" title-name">{this.state.title}</span>
                        <span ref='right' className="arrowright mui-icon mui-icon-arrowright"></span>
                    </p>
                </div>
            )
        }
    })

    var Root = r.createClass({
        getInitialState: function () {
            return {
                list: [{
                    reporterName: '',
                    reportTime: '',
                    content: '',
                    houseNum: ''
                }],
                user: '',
                maxCount: [],
                currType: '',
                fn:'',
            }
        },
        getList: function (page, shouldAppend, Fn) {
            if (!page) {
                page = 1;
            }
            this.state.fn = Fn;
            var me = this,
                typeAdd,
                typeFn;

            if (TYPE == UNTREATED) {//未处理
                typeFn = 0;
            } else if (TYPE == SENTED) {//已派单
                typeFn = 1;
            } else if (TYPE == COMPLETED) {//已完成
                typeFn = 2;
            } else if (TYPE == ARCHIVED) {//已归档
                typeFn = 3;
            } else if (TYPE == CLOSE) {//已关闭
                typeFn = 4;
            } else if (TYPE == QLLIGCP) {//待审核
                typeFn = 5;
            } else if (TYPE == CHECK) {//全部报事
                typeFn;
            }
            console.log(Fn)

            if (Fn == 'all'||Fn == undefined) {//日汇总
                typeAdd = 1;
                console.log('日汇总')
                ///日汇总
                ajax({
                    type: 'POST',
                    data: {
                        staffId: me.props.user.id,
                        eventReportType: typeFn,
                        timeType: typeAdd,
                        page: page,
                    },
                    success: function (data) {
                        if (data.code == '200') {

                            //let resultList = data.dataList;
                            let data = {
                                desc: "success",
                                maxCount: '10',
                                maxPage: '7',
                                pageSize: '10',
                            };
                            let resultList = [
                                    {
                                        id: "ff808181594309530159432a3cfc004e",
                                        snapped: "3600",
                                        confirm: '2500',
                                        Alipay:'555',
                                        createTime: 1482890559000,
                                        content: "苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃",
                                        total: 1482890559000,
                                        orderId:'1312312321132',
                                        eventId:'13712312302',
                                    }, {
                                        id: "ff808181594309530159432a3cfc004e",
                                        snapped: "3600",
                                        confirm: '2500',
                                        Alipay:'555',
                                        createTime: 1482890559000,
                                        content: "苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃",
                                        total: 1482890559000,
                                        orderId:'1312312321132',
                                        eventId:'13712312302',
                                    }, {
                                        id: "ff808181594309530159432a3cfc004e",
                                        snapped: "3600",
                                        confirm: '2500',
                                        Alipay:'555',
                                        createTime: 1482890559000,
                                        content: "真是的",
                                        total: 1482890559000,
                                        orderId:'1312312321132',
                                        eventId:'13712312302',
                                    }
                                ],
                                maxCount = data.maxCount,
                                appendedList;
                            console.log(resultList)
                            console.log(Fn)
                            if (shouldAppend) {
                                appendedList = me.state.list;
                                $.each(resultList, function (i, item) {
                                    appendedList.push(item);
                                });

                                mui('#pullrefresh')
                                    .pullRefresh()
                                    .endPullupToRefresh((appendedList.length == maxCount)); //refresh completed

                                me.setState({
                                    list: appendedList,
                                    currType: Fn,
                                    total: appendedList.length,
                                });
                            }
                            else {
                                me.setState({
                                    list: resultList,
                                    currType: Fn,
                                });
                            }
                        }
                        else {
                            alert(data.desc);
                        }
                    }
                }, lf.api.statistics.ReportListByStatus);
            } else if (Fn == 'month') {//销售明细
                typeAdd = 2;
                console.log('销售明细')
                //销售明细
                ajax({
                    type: 'POST',
                    data: {
                        staffId: me.props.user.id,
                        eventReportType: typeFn,
                        timeType: typeAdd,
                        page: page,
                    },
                    success: function (data) {
                        if (data.code == '200') {

                            //let resultList = data.dataList;
                            let data = {
                                desc: "success",
                                maxCount: '10',
                                maxPage: '7',
                                pageSize: '10',
                            };
                            let resultData = [
                                    {
                                        id: "ff808181594309530159432a3cfc004e",
                                        img: "../public/images/finger/apple.jpg",
                                        num: "A0402",
                                        createTime: 1482890559000,
                                        content: "苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃苹果甜又脆，好吃",
                                        createTime: 1482890559000,
                                        id: "ff808181594309530159432a3cfc004e",
                                        accepterName: "XIXI",
                                        text: "验证",
                                        totle: '1200',
                                        status: "0",
                                    },{
                                        id: "ff808181594309530159432a3cfc004e",
                                        img: "../public/images/finger/apple.jpg",
                                        num: "A0402",
                                        createTime: 1482890559000,
                                        content: "苹果甜又脆",
                                        createTime: 1482890559000,
                                        id: "ff808181594309530159432a3cfc004e",
                                        accepterName: "XIXI",
                                        text: "验证",
                                        totle: '1200',
                                        status: "0",
                                    },
                                ],
                                maxCount = data.maxCount,
                                appendedList;
                            console.log(resultData)
                            console.log(Fn)
                            if (shouldAppend) {
                                appendedList = me.state.list;
                                $.each(resultData, function (i, item) {
                                    appendedList.push(item);
                                });

                                mui('#pullrefresh')
                                    .pullRefresh()
                                    .endPullupToRefresh((appendedList.length == maxCount)); //refresh completed

                                me.setState({
                                    list: appendedList,
                                    currType: Fn,
                                    total: appendedList.length,
                                });
                            }
                            else {
                                me.setState({
                                    list: resultData,
                                    currType: Fn,
                                });
                            }
                        }
                        else {
                            alert(data.desc);
                        }
                    }
                }, lf.api.statistics.ReportListByStatus);
            }


        },
        componentWillMount: function () {
            var me = this;
            let timeList = [0, 1];//0:all,1:day,2:week,3:month
            timeList.map((i)=> {
                ajax({
                    type: 'POST',
                    data: {
                        staffId: me.props.user.id,
                        eventReportType: '',
                        timeType: i,
                    },
                    success: function (data) {
                        let list = me.state.maxCount;
                        list[i] = data.maxCount;
                        me.setState({
                            maxCount: list
                        })
                    }
                }, lf.api.statistics.ReportListByStatus)
            })
            me.getList();
            lf.appJs.refresh();
        },

        render: function () {
            return (
                <div className="list-census">
                    <SelectMonth />
                    <Header maxCount={this.state.maxCount} getList={this.getList} user={this.state.user}
                            counts={this.state.headerCounts } resetPage={this.props.resetPage}
                    />
                    {
                        this.state.fn == 'all'||this.state.fn == undefined?<ListGroup data={this.state.list} getList={this.getList} user={this.state.user}/>:
                            <LisTotal data={this.state.list} getList={this.getList} user={this.state.user}/>
                    }

                </div>
            )
        },
        componentWillReceiveProps: function (nextProps) {
            var page = nextProps.page;
            this.getList(page, true, this.state.currType);
        },
    });

    var PullRefreshCon = React.createClass({
        getInitialState: function () {
            return {
                page: 1,
            }
        },
        resetPage: function () {//todo 存在header 的上拉加载页面必须啊
            this.state.page = 1;
        },
        pullupFn: function () {
            var newPage = ++this.state.page;
            this.setState({
                page: newPage
            });
        },
        render: function () {
            var me = this;
            return <PullRefresh pullupFn={me.pullupFn}
                                data={<Root user={me.props.user} page={me.state.page} resetPage={me.resetPage}/>}/>;
        }
    });
    lf.appJs.getUser((user)=> {
        r.render(
            <PullRefreshCon user={user}/>,
            document.getElementById('root'), function () {
                $('#root').css('background', 'none');
            }
        )
    })
})(liefeng, React)